'use strict';

/* Controllers */

angular.module('spf2t.controllers', []).
controller('MyCtrl1', [function() {

}])
.controller('MyCtrl2', [function() {

}])

.controller('spf2tCtrl', ['$scope','$window', function($scope, $window) {
  function zeros(dimensions) {
    var array = [];
    for (var i = 0; i < dimensions[0]; ++i) {
      array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
    }
    return array;
  }

  var colors = ['red', 'blue', 'green', 'yellow']
  function randColor() {
    return colors[Math.floor(Math.random() * colors.length)];
  }

  $scope.gameStatus = "Kosher";

  $scope.blockNum = 0;

  $scope.newBlock = function () {
    return {
      x: 3,
      y: 14,
      id: ++$scope.blockNum,
      active: true,
      color: randColor(),
    }
  }

  // Controls box drop rate
  $scope.dY = 2;

  $scope.activeBlock = $scope.newBlock();
  $scope.blocks= [];

  $scope.gridId = 0;
  $scope.gridWidth = 6;
  $scope.gridHeight=14;
  $scope.gridIndex = zeros([$scope.gridWidth, $scope.gridHeight]);

  angular.element($window).bind("keydown", function(e) {
    // down 40
    if (e.which === 40 && $scope.activeBlock.x > 1) {
    console.log(e.which);
      e.preventDefault();
      $scope.dY=10;
    }
    else if (e.which === 38 && $scope.activeBlock.y < $scope.gridHeight) {
      e.preventDefault();
      var lowestBlock = 14;
      for(var i = lowestBlock; $scope.gridIndex[$scope.activeBlock.x][i] == 0; i--) {
        lowestBlock = i;
      }
        $scope.activeBlock.y = lowestBlock;
    }
    // left 37
    else if (e.which === 37 && $scope.activeBlock.x > 0) {
      e.preventDefault();
      if($scope.gridIndex[$scope.activeBlock.x - 1][$scope.activeBlock.y-1] == 0) {
        $scope.activeBlock.x--;
      }
    }
    // right 39
    else if (e.which === 39 && $scope.activeBlock.x < $scope.gridWidth-1) {
      e.preventDefault();
      if($scope.gridIndex[$scope.activeBlock.x + 1][$scope.activeBlock.y-1] == 0) {
        $scope.activeBlock.x++;
      }
    }


  });

  angular.element($window).bind("keyup", function(e) {
    console.log(e.which);
    // down 40
    if (e.which === 40 && $scope.activeBlock.x > 1) {
      $scope.dY = 2;
    }

  });


}]);


